﻿namespace TelecoSystems.Web.Services.Customers
{
    using System;
    using System.Data;
    using System.Linq;
    using System.ServiceModel.DomainServices.EntityFramework;
    using System.ServiceModel.DomainServices.Hosting;
    using TelecoSystems.Web.Models;
    using System.ServiceModel.DomainServices.Server;

    /// <summary>
    /// DomainService exposing domain logic operations for Customers module
    /// </summary>
    [RequiresRole("Dealer")]
    [RequiresAuthentication]
    [EnableClientAccess()]
    public class CustomersDomainService : LinqToEntitiesDomainService<TelecoSystemsContainer>
    {        
        public IQueryable<Customer> GetCustomers()
        {
            return this.ObjectContext.Customers;
        }

        public IQueryable<CustomerCompany> GetCompanyCustomers()
        {
            return this.ObjectContext.Customers.OfType<CustomerCompany>();
        }

        public IQueryable<CustomerPerson> GetPersonCustomers() {
            return this.ObjectContext.Customers.OfType<CustomerPerson>();
        }

        public void InsertCustomer(Customer customer)            
        {
            //Set not editable attributes
            customer.DateCreated = customer.DateLastModified = DateTime.Now;

            //Calculate id for the new record
            if (this.ObjectContext.Customers.Count() > 0)
            {
                customer.Id = this.ObjectContext.Customers.Max(c => c.Id) + 1;
            }
            else
            {
                customer.Id = 1;
            }            
            
            if ((customer.EntityState != EntityState.Detached))
            {
                this.ObjectContext.ObjectStateManager.ChangeObjectState(customer, EntityState.Added);
            }
            else
            {
                this.ObjectContext.Customers.AddObject(customer);
            }
        }

        public void UpdateCustomer(Customer currentCustomer)
        {
            this.ObjectContext.Customers.AttachAsModified(currentCustomer, this.ChangeSet.GetOriginal(currentCustomer));
        }

        public void DeleteCustomer(Customer customer)
        {
            if ((customer.EntityState == EntityState.Detached))
            {
                this.ObjectContext.Customers.Attach(customer);
            }
            this.ObjectContext.Customers.DeleteObject(customer);
        }       
    }
}